package com.ctzj.isale;

import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.lang.reflect.Method;

/**
 * Author:  <a href="haif.yao@gmail.com">ivan</a>
 * Date: 14-11-26
 */
public class MethodCacheKeyGenerator {

    public static final int NO_PARAM_KEY = 0;
    public static final int NULL_PARAM_KEY = 53;

    private Object target;
    private Method method;
    private int hashCodeKey = 17;
    private boolean hasParam = false;

    public MethodCacheKeyGenerator(Object target, Method method) {
        this.target = target;
        this.method = method;
    }


    private void cal(int newHashCode) {
        hashCodeKey = 31 * hashCodeKey + newHashCode;
        hasParam = true;
    }

    /**
     * 根据默认的方法生成HashCode
     *
     * @param obj
     * @return
     */
    public MethodCacheKeyGenerator appendDef(Object obj) {
        int newHashCode = (obj == null ? NULL_PARAM_KEY : obj.hashCode());
        cal(newHashCode);

        return this;
    }

    /**
     * 反射地方式根据每个属性生成HashCode
     *
     * @param obj
     * @return
     */
    public MethodCacheKeyGenerator appendRefl(Object obj) {
        int newHashCode = (obj == null ? NULL_PARAM_KEY : HashCodeBuilder.reflectionHashCode(obj));
        cal(newHashCode);

        return this;
    }

    public String generate() {
        String methodName = method.getName();

        StringBuilder sb = new StringBuilder()
                .append(methodName)
                .append("_")
                .append(hasParam ? hashCodeKey : NO_PARAM_KEY);
        return sb.toString();
    }
}
